import type { LoginResult } from '@/types/member'
import { getUser } from '@/services/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const userInfoStore = defineStore(
  'member',
  () => {
    const storage = {
      getItem(key: string) {
        return uni.getStorageSync(key)
      },
      setItem(key: string, value: any) {
        uni.setStorageSync(key, value)
      },
    }
    // 会员信息
    const profile = ref<LoginResult>()
    const isWx = ref(0) //0 微信   //1 其他
    const token = ref('')
    const city = ref('')

    const getUserInfo = () => {
      getUser().then((res) => {
        const obj = Object.assign({}, profile.value, res)
        profile.value = obj
        storage.setItem('xam:user', obj)
      })
    }

    const setDevice = (val: any) => {
      isWx.value = val
      storage.setItem('isWx', val)
    }

    // 保存会员信息，登录时使用
    const setProfile = (val: any) => {
      // console.log(profile.value)
      // console.log("profile.value")
      const obj = Object.assign({}, profile.value, val)
      profile.value = obj
      uni.setStorageSync('xam:user', obj)
    }

    const setData = (key: any, val: any) => {
      storage.setItem(key, val)
    }
    const getData = (key: any) => {
      return uni.getStorageSync(key)
    }
    const getProfile = (val: any) => {
      return uni.getStorageSync(val)
    }
    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
      uni.removeStorageSync('xam:user')
    }

    // 记得 return
    return {
      setData,
      getData,
      profile,
      city,
      setProfile,
      getProfile,
      clearProfile,
      setDevice,
      isWx,
      getUserInfo,
      token,
    }
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },
  },
)
